<?php   if (!defined('BASEPATH')) exit('No direct script access allowed');


class Missioni_model extends CI_Model {
	
    function __construct()
    {
        parent::__construct();
    }

    function get_columns()
	{
		$sql = "SELECT column_name from information_schema.columns where
table_name='" . $this->db->dbprefix('missioni') . "'";
		$query = $this->db->query($sql);
		
		return $query->result_array();
	}
	
	function get_total($params = array())
	{
		$default_params = array
		(
			'where' => null
		);
        
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
        
		$this->db->select('count(id) as nb');
		$this->db->where ($params['where']);
        $query = $this->db->get('missioni');
        
		$row = $query->row();
		return $row->nb;
	}
	
	function get_rimesse()
	{
		$this->db->order_by('nome');
		$query = $this->db->get('rimesse');
		if($query->num_rows() > 0)
		{
			return $query->result_array();
		}
		else
		{
			return false;
		}
	}

    
    function get_list($params = array())
    {
 		$default_params = array
		(
			'select' => 'm.*, r.nome as rimessa',
			'order_by' => 'nome',
			'limit' => 100,
			'where' => 'attivo = 1',
			'start' => 0,
		);
		
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
       $sql = "SELECT " . $params['select'] . " FROM missioni m LEFT JOIN rimesse r ON m.id_rimesse=r.id WHERE " . $params['where'] . " ORDER BY " . $params['order_by'];
        $query = $this->db->query($sql);
        
        return $query->result_array();
   
    }
    
    function get($params = array())
    {
 		$default_params = array
		(
			'select' => '*',
			'order_by' => 'nome',
			'where' => 'attivo = 1',
		);
		
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
       $sql = "SELECT " . $params['select'] . " FROM missioni WHERE " . $params['where'] . " ORDER BY " . $params['order_by'] . " LIMIT 1";
        $query = $this->db->query($sql);
        
        return $query->row_array();
   
    }
	

    function delete($where)
	{
        $this->db->where($where);
		$this->db->delete('missioni');
        $true = $this->db->affected_rows() > 0; 
		return $true;
	}
    
    function save($data)
    {
        
   		if(!isset($data['id']) || !$data['id'])
        {
            $query = $this->db->query("SELECT max(id) as id FROM missioni");
            $row = $query->row_array();
            $data['id'] = $row['id']+1;
			$data['username'] = $this->user->username;
            
            $this->db->insert('missioni', $data);
        }
        else
        {
            $this->db->where('id', $data['id']);
			
            $this->db->update('missioni', $data);
        }
		return $data['id'];

    }
	
}